<template>
  <BasicModal
      v-bind="$attrs"
      @register="registerModal"
      :title="`证照附件 - ${record.name || ''}`"
      :width="700"
      @ok="handleOk"
  >
    <div class="attachment-container">
      <Spin :spinning="loading">
        <!-- 证照基本信息 -->
        <div class="certificate-info mb-4">
          <a-descriptions :column="2" bordered size="small">
            <a-descriptions-item label="证照名称" :span="2">{{ record.name }}</a-descriptions-item>
            <a-descriptions-item label="证照编号">{{ record.no }}</a-descriptions-item>
            <a-descriptions-item label="持证人">{{ record.holdusername }}</a-descriptions-item>
          </a-descriptions>
        </div>

        <!-- 附件列表 - 使用表格形式 -->
        <div class="attachment-section">
          <a-divider style="border-color: #ccc" dashed />
          <a-typography-title :level="4">附件列表</a-typography-title>

          <!-- 使用表格显示附件 -->
          <a-table
              v-if="attachments.length > 0"
              :columns="columns"
              :data-source="attachments"
              :pagination="false"
              size="small"
              :row-key="(record) => record.id || record.name"
          >
            <!-- 文件名列自定义渲染 -->
            <template #bodyCell="{ column, record }">
              <!-- 文件名和图标 -->
              <template v-if="column.dataIndex === 'name'">
                <span class="file-type-icon">
                  <FilePdfOutlined v-if="isPdf(record)" class="pdf-icon" />
                  <FilePptOutlined v-else-if="isPpt(record)" class="ppt-icon" />
                  <FileWordOutlined v-else-if="isWord(record)" class="word-icon" />
                  <FileImageOutlined v-else-if="isImage(record)" class="image-icon" />
                  <FileTextOutlined v-else />
                </span>
                <span>{{ record.name }}</span>
              </template>


              <!-- 上传时间列 -->
              <template v-if="column.dataIndex === 'uploadTime'">
                {{ formatDate(record.uploadTime) }}
              </template>

              <!-- 操作列 -->
              <template v-if="column.dataIndex === 'action'">
                <a-button type="link" size="small" @click="handleView(record)">
                  <template #icon><EyeOutlined /></template>
                  查看
                </a-button>
              </template>
            </template>
          </a-table>

          <!-- 无附件时显示 -->
          <div v-else class="no-attachments">
            <a-empty description="暂无附件信息" />
          </div>

          <!-- 图片预览区域 (可选，根据需要决定是否保留) -->
          <!--          <div v-if="hasImageAttachments" class="image-preview-section">
            <a-divider orientation="left">图片预览</a-divider>
            <div class="image-list">
              <div v-for="item in imageAttachments" :key="item.id" class="image-item">
                <a-image
                    :width="100"
                    :src="item.path || item.url"
                    :preview="false"
                    @click="previewImage(item)"
                />
                <div class="image-name">{{ item.name }}</div>
              </div>
            </div>
          </div>-->
        </div>
      </Spin>

      <!-- 图片预览对话框 -->
      <a-modal
          v-model:visible="previewVisible"
          :title="previewTitle"
          :footer="null"
          :width="800"
          @cancel="handlePreviewCancel"
      >
        <div class="preview-container">
          <img
              :src="previewImageUrl"
              alt="附件预览"
              style="max-width: 100%; max-height: 500px;"
          />
        </div>
      </a-modal>
    </div>
  </BasicModal>
</template>

<script lang="ts">
import {defineComponent, ref, computed, onMounted} from 'vue';
import {BasicModal, useModalInner} from '/@/components/Modal';
import {Button, Descriptions, Divider, Empty, Image,Modal, Spin, Table, Typography} from 'ant-design-vue';
import {
  EyeOutlined,
  FilePdfOutlined,
  FilePptOutlined,
  FileWordOutlined,
  FileImageOutlined,
  FileTextOutlined
} from '@ant-design/icons-vue';
import {useMessage} from '/@/hooks/web/useMessage';
import {downloadByUrl} from '/@/utils/file/download';
import {
  uploadFileApi,
  getImageFileApi,
  getPdfFileApi,
  getFileApi
} from "/@/api/platform/file";
import {useGlobSetting} from '/@/hooks/setting';

export default defineComponent({
  name: 'AttachmentModal',
  components: {
    BasicModal,
    ADescriptions: Descriptions,
    ADescriptionsItem: Descriptions.Item,
    ATable: Table,
    AButton: Button,
    AImage: Image,
    AModal: Modal,
    Spin,
    AEmpty: Empty,
    ADivider: Divider,
    ATypographyTitle: Typography.Title,
    EyeOutlined,
    FilePdfOutlined,
    FilePptOutlined,
    FileWordOutlined,
    FileImageOutlined,
    FileTextOutlined,
  },
  setup() {
    const { createMessage } = useMessage();
    const record = ref({});
    const attachments = ref([]);
    const loading = ref(false);

    // 获取全局设置
    const { uploadUrl } = useGlobSetting();

    // 文件访问URL前缀
    const imageFileUrlPrefix = uploadUrl + getImageFileApi;
    const pdfFileUrlPrefix = uploadUrl + getPdfFileApi;
    const fileUrlPrefix = uploadUrl + getFileApi;

    // 预览相关状态
    const previewVisible = ref(false);
    const previewTitle = ref('');
    const previewImageUrl = ref('');

    // 表格列定义
    const columns = [
      {
        title: '文件名',
        dataIndex: 'name',
        key: 'name',
        width: 150,
      },
      {
        title: '类型',
        dataIndex: 'type',
        key: 'type',
        width: 100,
      },

      {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        width: 150,
        align: 'center',
      },
    ];

    // 是否有图片附件
    const hasImageAttachments = computed(() => {
      return attachments.value.some(item => isImage(item));
    });

    // 获取图片附件列表
    const imageAttachments = computed(() => {
      return attachments.value.filter(item => isImage(item));
    });

    // 注册模态框
    const [registerModal, { closeModal }] = useModalInner((data) => {
      record.value = data.record || {};
      // 解析附件信息
      parseAttachments();
    });

    //更具文件id和文件类型获取文件URL
    function getFileUrl(file){
      if (!file || !file.id) return '';

      const fileId = file.id;
      const fileType = file.type || '';

      if (['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(fileType.toLowerCase())) {
        return imageFileUrlPrefix + fileId;
      } else if (fileType.toLowerCase() === 'pdf') {
        return pdfFileUrlPrefix + fileId;
      } else {
        return fileUrlPrefix + fileId;
      }
    }

    // 解析附件JSON数据
    function parseAttachments() {
      loading.value = true;

      try {
        if (record.value.attachment) {
          // 尝试解析JSON
          let attachmentData = record.value.attachment;

          // 如果是字符串，尝试解析成JSON
          if (typeof attachmentData === 'string') {
            try {
              attachmentData = JSON.parse(attachmentData);
            } catch (e) {
              console.error('解析附件JSON失败:', e);
              attachments.value = [];
              return;
            }
          }

          // 处理不同的数据结构
          if (Array.isArray(attachmentData)) {
            // 如果是数组，直接使用
            attachments.value = attachmentData;
          } else if (attachmentData.files && Array.isArray(attachmentData.files)) {
            // 如果有files属性且是数组
            attachments.value = attachmentData.files;
          } else {
            // 其他情况，将整个对象作为单个附件
            attachments.value = [attachmentData];
          }
        } else {
          attachments.value = [];
        }
      } catch (error) {
        console.error('处理附件数据出错:', error);
        createMessage.error('解析附件信息失败');
        attachments.value = [];
      } finally {
        loading.value = false;
      }
    }

    // 格式化日期
    function formatDate(dateStr) {
      if (!dateStr) return '未知';

      try {
        const date = new Date(dateStr);
        if (isNaN(date.getTime())) return dateStr;

        return date.toLocaleDateString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit'
        }) + ' ' + date.toLocaleTimeString('zh-CN', {
          hour: '2-digit',
          minute: '2-digit',
          hour12: false
        });
      } catch (e) {
        return dateStr;
      }
    }

    // 判断是否是图片
    function isImage(file) {
      if (!file) return false;

      const name = file.name || '';
      const type = file.type || '';
      const path = file.path || '';

      return type.includes('image') ||
          type === 'jpg' || type === 'jpeg' || type === 'png' || type === 'gif' ||
          name.toLowerCase().endsWith('.jpg') || name.toLowerCase().endsWith('.jpeg') ||
          name.toLowerCase().endsWith('.png') || name.toLowerCase().endsWith('.gif') ||
          path.toLowerCase().endsWith('.jpg') || path.toLowerCase().endsWith('.jpeg') ||
          path.toLowerCase().endsWith('.png') || path.toLowerCase().endsWith('.gif');
    }

    // 判断是否是PDF
    function isPdf(file) {
      if (!file) return false;

      const name = file.name || '';
      const type = file.type || '';
      const path = file.path || '';

      return type.includes('pdf') || type === 'pdf' ||
          name.toLowerCase().endsWith('.pdf') ||
          path.toLowerCase().endsWith('.pdf');
    }

    // 判断是否是PPT
    function isPpt(file) {
      if (!file) return false;

      const name = file.name || '';
      const type = file.type || '';
      const path = file.path || '';

      return type.includes('ppt') || type === 'ppt' || type === 'pptx' ||
          name.toLowerCase().endsWith('.ppt') || name.toLowerCase().endsWith('.pptx') ||
          path.toLowerCase().endsWith('.ppt') || path.toLowerCase().endsWith('.pptx');
    }

    // 判断是否是Word文档
    function isWord(file) {
      if (!file) return false;

      const name = file.name || '';
      const type = file.type || '';
      const path = file.path || '';

      return type.includes('doc') || type === 'doc' || type === 'docx' ||
          name.toLowerCase().endsWith('.doc') || name.toLowerCase().endsWith('.docx') ||
          path.toLowerCase().endsWith('.doc') || path.toLowerCase().endsWith('.docx');
    }

    // 预览图片
    function previewImage(file) {
      previewImageUrl.value = getFileUrl(file);
      previewTitle.value = file.name || '图片预览';
      previewVisible.value = true;
    }

    // 处理查看 - 根据文件类型决定显示还是下载
    function handleView(file) {

      if (isImage(file)) {
        // 显示图片预览
        previewImage(file);
      } else {
        // 非图片直接下载
        handleDownload(file);
      }
    }

    // 关闭预览
    function handlePreviewCancel() {
      previewVisible.value = false;
      previewImageUrl.value = '';
    }

    // 处理下载
    function handleDownload(file) {
      if (!file) {
        createMessage.error('文件信息不存在');
        return;
      }

      const url = getFileUrl(file);
      if (!url) {
        createMessage.error('无法下载，文件路径不存在');
        return;
      }

      const fileName = file.name || '附件';

      // 使用系统内置的下载函数
      const result = downloadByUrl({
        url: url,
        fileName: fileName + (file.type ? ('.' + file.type) : '')
      });
      if (result) {
        // 下载成功，显示提示
        createMessage.success(`正在下载: ${fileName}`);
      } else {
        // 下载失败，显示错误提示
        createMessage.error('下载失败，您的浏览器可能不支持此操作');
      }

    }

    // 处理确认按钮
    function handleOk() {
      closeModal();
    }


    return {
      registerModal,
      record,
      loading,
      attachments,
      columns,
      hasImageAttachments,
      imageAttachments,
      previewVisible,
      previewTitle,
      previewImageUrl,
      formatDate,
      isImage,
      isPdf,
      isPpt,
      isWord,
      previewImage,
      handleView,
      handlePreviewCancel,
      handleOk,
    };
  },
});
</script>

<style lang="less" scoped>
.attachment-container {
  padding: 16px;
}

.certificate-info {
  margin-bottom: 20px;
}

.attachment-section {
  margin-top: 10px;
}

.file-type-icon {
  margin-right: 8px;

  .pdf-icon {
    color: #ff5252;
  }

  .word-icon {
    color: #4285f4;
  }

  .ppt-icon {
    color: #ff7043;
  }

  .image-icon {
    color: #43a047;
  }
}

.no-attachments {
  padding: 30px 0;
  display: flex;
  justify-content: center;
}

.image-preview-section {
  margin-top: 20px;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  margin: 10px 0;
}

.image-item {
  margin: 5px;
  text-align: center;
}

.image-name {
  margin-top: 5px;
  font-size: 12px;
  width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}
</style>
